package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.OutsideTemperatureHis;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.OutsideTemperatureHisService;
import com.bbzn.device.client.utils.OptionalBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:19
 * @Version 1.0
 */
@Component
public class EmqTemperatureStrategy implements EmqStrategy {

    @Resource
    private OutsideTemperatureHisService outsideTemperatureHisService;

    @Autowired
    private DeviceService deviceService;

    // 实时检测环境温度 设备响应结果
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }

            String temperature = jsonObject.getString("temperature");
            if (!OptionalBean.ofNullable(temperature).isPresent()) {
                return "json解析错误";
            }
            OutsideTemperatureHis outsideTemperatureHis = new OutsideTemperatureHis();
            outsideTemperatureHis.setImei(imei);
            outsideTemperatureHis.setTemperature(Double.valueOf(temperature));
            outsideTemperatureHis.setCreateTime(new Date()); //new Timestamp(System.currentTimeMillis())
            outsideTemperatureHis.setCreatedBy("emq");
            outsideTemperatureHisService.insertSelective(outsideTemperatureHis);

            Device device = new Device();
            device.setImei(imei);
            device.setTemperature(Double.valueOf(temperature));
            device.setTemperatureState(0);
            deviceService.updateByImeiSelective(device);
        } catch (Exception e) {
            return "获取环境温度值失败！";
        }
        return "获取环境温度值成功！";
    }
}
